package com.bw.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Dws_User_shop_uv {
    public static void main(String[] args) throws Exception {

        // TODO 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 3. 从 kafka dwd_traffic_page_log 主题读取日志数据，封装为流
        String topic = "dwd_traffic_page_log_project_shop";
        String groupId = "dwd_traffic_uv_detail";
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> pageLog = env.addSource(kafkaConsumer);

//        pageLog.print();



        // TODO 4. 转换结构
        SingleOutputStreamOperator<JSONObject> mappedStream = pageLog.flatMap(
                new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(value);
                            out.collect(jsonObj);
                        } catch (Exception e) {
                            System.out.println("脏数据:"+value);
                        }
                    }
                }
        );
//
        SingleOutputStreamOperator<JSONObject> firstPageStream = mappedStream.filter(
                jsonObj -> jsonObj
                        .getJSONObject("page")
                        .getString("last_page_id") == null
        );
//
//        // TODO 6. 按照 mid 分组
        KeyedStream<JSONObject, Tuple2<String, String>> keyedStream = firstPageStream
                .keyBy(new KeySelector<JSONObject, Tuple2<String, String>>() {
                    @Override
                    public Tuple2<String, String> getKey(JSONObject value) throws Exception {
                        String mid = value.getJSONObject("common").getString("mid");
                        String shopId = value.getJSONObject("common").getString("shop_id"); // 修正字段名
                        return new Tuple2<>(mid, shopId); // 正确使用变量
                    }
                });
//
//        // TODO 7. 通过 Flink 状态编程过滤独立访客记录
        SingleOutputStreamOperator<JSONObject> filteredStream = keyedStream.filter(
                new RichFilterFunction<JSONObject>() {
                    private ValueState<String> lastVisitDt;
                    private ValueState<String> hour12q; // 上午状态
                    private ValueState<String> hour12h; // 下午状态

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        ValueStateDescriptor<String> valueStateDescriptor =
                                new ValueStateDescriptor<>("last_visit_dt", String.class);
                        // 配置状态的生命周期
                        valueStateDescriptor.enableTimeToLive(
                                StateTtlConfig
                                        .newBuilder(Time.days(1L))
                                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                        .build()
                        );
                        this.lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
                        this.hour12q = getRuntimeContext().getState(new ValueStateDescriptor<>("hour_12q", String.class));
                        this.hour12h = getRuntimeContext().getState(new ValueStateDescriptor<>("hour_12h", String.class));
                    }

                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String visitDt = DateFormatUtil.toDate(jsonObj.getLong("ts"));
                        DateFormat dateFormat = new SimpleDateFormat("HH");
                        String aa = dateFormat.format(jsonObj.getLong("ts"));
                        int currentHour = Integer.parseInt(aa);

                        String lastDt = lastVisitDt.value();
                        String hourq = hour12q.value();
                        String hourh = hour12h.value();

                        boolean shouldKeep = false;

                        // 更新总的访问日期
                        if (lastDt == null || !lastDt.equals(visitDt)) {
                            lastVisitDt.update(visitDt);
                        }

                        if (currentHour <= 12) {
                            // 上午时间段（0-12点）
                            if (hourq == null || !hourq.equals(visitDt)) {
                                hour12q.update(visitDt);
                                shouldKeep = true;
                            }
                        } else {
                            // 下午时间段（13-23点）
                            if (hourh == null || !hourh.equals(visitDt)) {
                                hour12h.update(visitDt);
                                shouldKeep = true;
                            }
                        }

                        return shouldKeep;
                    }
                }
        );
//        // TODO 8. 将独立访客数据写入
        // Kafka dwd_traffic_unique_visitor_detail 主题
        String targetTopic = "dwd_traffic_unique_visitor_detail_project";
        filteredStream.print(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        FlinkKafkaProducer<String> kafkaProducer = MyKafkaUtil.getFlinkKafkaProducer(targetTopic);
        filteredStream.map(a->a.toJSONString()).addSink(kafkaProducer);
        // TODO 9. 启动任务
        env.execute();
    }
}
